package com.ridaizu.bean;

import java.io.Serializable;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.LazyDataModel;

import com.google.common.base.Strings;
import com.ridaizu.cache.CacheDataBean;
import com.ridaizu.dao.db.DBManager;
import com.ridaizu.lazy.LazyDictionaryDataModel;
import com.ridaizu.model.Dictionary;
import com.ridaizu.model.form.DictionaryForm;
import com.ridaizu.model.search.DictionarySearch;
import com.ridaizu.service.impl.DictionaryServiceImpl;
import com.ridaizu.util.DateUtil;

@javax.faces.bean.ManagedBean(name = "dictionaryBean")
@SessionScoped
public class DictionaryBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private LazyDataModel<Dictionary> lazyModel;

    @ManagedProperty("#{cacheDataBean}")
    private CacheDataBean cacheDataBean;

    @ManagedProperty("#{dictionaryServiceImpl}")
    private DictionaryServiceImpl dictionaryService;

    @ManagedProperty("#{dictionarySearch}")
    private DictionarySearch dictionarySearch;

    @ManagedProperty("#{dictionaryForm}")
    private DictionaryForm dictionaryForm;

	public void searchDictionarySync() {
		lazyModel = new LazyDictionaryDataModel(dictionarySearch);
	}

	public void viewRegisterDictionary() throws SQLException {

		setInitValues(null);

        Map<String,Object> options = new HashMap<String, Object>();
        options.put("modal", true);
        options.put("contentWidth", 550);
        options.put("contentHeight", 200);

        RequestContext.getCurrentInstance().openDialog("dictionary", options, null);
    }

	public void viewUpdateDictionary(Dictionary dictionary) throws SQLException {

		setInitValues(dictionary);

        Map<String,Object> options = new HashMap<String, Object>();
        options.put("modal", true);
        options.put("contentWidth", 550);
        options.put("contentHeight", 220);

        RequestContext.getCurrentInstance().openDialog("dictionary", options, null);
    }

	private void setInitValues(Dictionary dictionary) throws SQLException {
		dictionaryForm.clearAll();
		setValues(dictionary);
	}

	private void setValues(Dictionary dictionary) {
		if (dictionary == null) {
			setRegisterValues();
		} else {
			setUpdateValues(dictionary);
		}
	}

	private void setRegisterValues() {
	}

	private void setUpdateValues(Dictionary dictionary) {
		dictionaryForm.setId(String.valueOf(dictionary.getId()));
		dictionaryForm.setType(String.valueOf(dictionary.getType()));
		dictionaryForm.setName(dictionary.getName());
		dictionaryForm.setRgtOpt(dictionary.getRgtOpt());
		dictionaryForm.setRgtDate(new Date(dictionary.getRgtDate().getTime()));
		dictionaryForm.setUpdOpt(dictionary.getUpdOpt());
		dictionaryForm.setUpdDate(new Date(dictionary.getUpdDate().getTime()));
	}

	public void registerDictionary() {
		Dictionary dictionary = getDictionary();

		boolean result = false;

		try {
			DBManager.beginTransaction();
			result = dictionaryService.insertModel(dictionary);
			DBManager.commitTransaction();

		} catch (SQLException e) {
			e.printStackTrace();
			result = false;
			DBManager.rollbackTransaction();
		}

		RequestContext.getCurrentInstance().closeDialog(result);
    }

	public void updateDictionary() {

		Dictionary dictionary = getDictionary();

		boolean result = false;

		try {
			DBManager.beginTransaction();
			result = dictionaryService.updateModel(dictionary);
			DBManager.commitTransaction();

		} catch (SQLException e) {
			e.printStackTrace();
			result = false;
			DBManager.rollbackTransaction();
		}

		RequestContext.getCurrentInstance().closeDialog(result);
	}

	public void deleteDictionary() {

		Dictionary selectedDictionary = dictionaryForm.getSelectedDictionary() ;

		if (selectedDictionary == null || selectedDictionary.getId() < 1) {
	        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message", "请选择要删除的数据字典信息。");
	        FacesContext.getCurrentInstance().addMessage(null, message);

	        return ;
		}

		boolean result = false;
		try {
			DBManager.beginTransaction();
			result = dictionaryService.deleteModel(selectedDictionary.getId());
			DBManager.commitTransaction();
		} catch (SQLException e) {
			e.printStackTrace();
			result = false;
			DBManager.rollbackTransaction();
		}

		String resultStr = null;
		if (result) {
			resultStr = String.format("数据字典[%s]删除成功。", selectedDictionary.getId());
		} else {
			resultStr = String.format("数据字典[%s]删除失败。", selectedDictionary.getId());
		}

        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Dictionary delete result", resultStr);
        FacesContext.getCurrentInstance().addMessage(null, message);
	}

	public void registerDictionaryResult(SelectEvent event) {
		boolean result = (Boolean) event.getObject();

		handleResult(result, "登录");
	}

	public void updateDictionaryResult(SelectEvent event) {

		boolean result = (Boolean) event.getObject();

		handleResult(result, "更新");
	}

	private void handleResult(boolean result, String optStr) {

		String resultStr = null;
		if (result) {
			resultStr = String.format("数据字典信息%s成功。", optStr);
		} else {
			resultStr = String.format("数据字典信息%s失败。", optStr);;
		}

        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message", resultStr);

        FacesContext.getCurrentInstance().addMessage(null, message);
	}

	private Dictionary getDictionary() {

		Dictionary dictionary = new Dictionary();

		if (!Strings.isNullOrEmpty(dictionaryForm.getId())) {
			dictionary.setId(Integer.valueOf(dictionaryForm.getId()));
		}

		if (!Strings.isNullOrEmpty(dictionaryForm.getType())) {
			dictionary.setType(Integer.valueOf(dictionaryForm.getType()));
		}

		dictionary.setName(dictionaryForm.getName());

		Timestamp currentDate = DateUtil.getCurrentDateTime();

		dictionary.setRgtOpt("Admin");
		dictionary.setRgtDate(currentDate);
		dictionary.setUpdOpt("Admin");
		dictionary.setUpdDate(currentDate);

		return dictionary;
	}

	public LazyDataModel<Dictionary> getLazyModel() {
		return lazyModel;
	}

	public void setLazyModel(LazyDataModel<Dictionary> lazyModel) {
		this.lazyModel = lazyModel;
	}

	public DictionaryServiceImpl getDictionaryService() {
		return dictionaryService;
	}

	public void setDictionaryService(DictionaryServiceImpl dictionaryService) {
		this.dictionaryService = dictionaryService;
	}

	public DictionarySearch getDictionarySearch() {
		return dictionarySearch;
	}

	public void setDictionarySearch(DictionarySearch dictionarySearch) {
		this.dictionarySearch = dictionarySearch;
	}

	public DictionaryForm getDictionaryForm() {
		return dictionaryForm;
	}

	public void setDictionaryForm(DictionaryForm dictionaryForm) {
		this.dictionaryForm = dictionaryForm;
	}

	public CacheDataBean getCacheDataBean() {
		return cacheDataBean;
	}

	public void setCacheDataBean(CacheDataBean cacheDataBean) {
		this.cacheDataBean = cacheDataBean;
	}

}